package service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import dao.ApartmentDao;
import dao.ApartmentDaoFactory;
import dao.DormitoryDao;
import dao.DormitoryDaoFactory;
import dao.StudentDao;
import dao.StudentDaoFactory;
import entity.Apartment;
import entity.Dormitory;
import entity.Student;
import service.EnterSch;

public class EnterSchImpl implements EnterSch{
	Scanner scanner = new Scanner(System.in);
	@Override
	public boolean enterSchool(Student student) {
		// TODO Auto-generated method stub
		ApartmentDao apartmentDao = ApartmentDaoFactory.getApartmentDao();
		List<Apartment> as = apartmentDao.findAll();
		List<Apartment> aparts = new ArrayList<>();	//符合相同性别的公寓集合
		for (Apartment a : as) {
			if(a.getSex().equals(student.getSex())) {
				aparts.add(a);
			}
		}
		System.out.println("请选择公寓id");
		for (Apartment a : aparts) {
			System.out.println(a.getId()+"\t");
		}
		int id_apart = scanner.nextInt();
		DormitoryDao dormitoryDao = DormitoryDaoFactory.getDormitoryDao();
		List<Dormitory> ds = dormitoryDao.findAll();
		List<Dormitory> dorms = new ArrayList<>();
		for (Dormitory d : ds) {		//选择公寓里边还有空位的宿舍房间
			if((d.getId_apart() == id_apart) && d.getSize()<d.getCapacity()) {
				dorms.add(d);
			}
		}
		if(dorms.size() <=0) {
			System.out.println("该公寓没有多余床位, 添加失败, 退出");
			return false;
		}
		
		System.out.println("请选择宿舍id: ");
		for (Dormitory dormitory : dorms) {
			System.out.println(dormitory.getId()+"\t");
		}
		int id_dorm = scanner.nextInt();
		StudentDao studentDao = StudentDaoFactory.getStudentDao();
//		List<Student> ss = studentDao.findAll();
//		List<Student> students = new ArrayList<>();
//		for (Student s : ss) {
//			if((s.getId_apart() == id_apart) && (s.getId_dorm() == id_dorm)) {
//				students.add(s);
//			}
//		}
		System.out.println("你选择的 id_dorm "+id_dorm+" id_apart "+id_apart);
		List<Student> students = studentDao.findRoommate(id_dorm, id_apart);
		System.out.println("你的舍友 的床号有: ");
		for (Student s : students) {
			System.out.print(s.getId_bed()+"\t");
		}
		System.out.println("\n输入你的床号: ");
		int id_bed = scanner.nextInt();
		
		//同步数据库
		Apartment apartment = apartmentDao.find(id_apart);
		apartment.setNum_stu(apartment.getNum_stu() + 1);
		boolean b1 = apartmentDao.update(apartment);
		
		Dormitory dormitory = dormitoryDao.find(id_dorm, id_apart);
		dormitory.setSize(dormitory.getSize() + 1);
		boolean b2 = dormitoryDao.update(dormitory);
		
		student.setId_apart(id_apart);
		student.setId_dorm(id_dorm);
		student.setId_bed(id_bed);
		boolean b3 = studentDao.insert(student);	//新学生,不是 update
		System.out.println("b1, b2, b3: "+b1+b2+b3);
		if(b1 && b2 && b3) {
			return true;
		}
		
		return false;
	}

}
